package com.factory.iamp.service.impl;

import com.factory.iamp.dao.UploadMapper;
import com.factory.iamp.pojo.Upload;
import com.factory.iamp.pojo.UploadList;
import com.factory.iamp.pojo.User;
import com.factory.iamp.service.UploadService;
import com.factory.iamp.utils.exception.APIException;
import com.factory.iamp.utils.helper.FileUploadHelper;
import com.factory.iamp.utils.helper.PageHelper;
import com.factory.iamp.utils.helper.ResponseCode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

@Service
@Transactional(rollbackFor = Throwable.class)
public class UploadServiceImpl implements UploadService {
    @Resource
    private UploadMapper uploadMapper;

    @Override
    public int Count() {
        return uploadMapper.Count();
    }

    @Override
    public int MyCount(String uid) {
        return uploadMapper.MyCount(uid);
    }

    @Override
    public List<UploadList> getTableFile(int tid) {
        return uploadMapper.getTableFile(tid);
    }

    @Override
    public List<UploadList> getContentFile(int oid) {
        return uploadMapper.getContentFile(oid);
    }

    @Override
    public List<UploadList> ListPaged(PageHelper data) {
        return uploadMapper.ListPaged(data.calOffset(), data.getLimit());
    }

    @Override
    public List<UploadList> MyListPaged(PageHelper data, String uid) {
        return uploadMapper.MyListPaged(data.calOffset(), data.getLimit(), uid);
    }

    @Override
    public Upload addFileSingle(User user, MultipartFile file, int tid) throws Throwable {
        String originName = file.getOriginalFilename();
        assert originName != null;
        String fileExtension = originName.substring(originName.lastIndexOf("."));
        LocalDate date = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
        String uid = user.getUid();
        String serverName = date.format(formatter) + "-" + uid + "-" +UUID.randomUUID() + fileExtension;
        formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        String filePath = "/data/upload/" + date.format(formatter) + "/";
        FileUploadHelper.upload(filePath, serverName, file);
        Upload upload = new Upload();
        upload.insertBuild(uid, tid, originName, filePath + serverName);
        uploadMapper.addFileSingle(upload);
        return upload;
    }

    @Override
    public void deleteMyFile(User user, int fid) {
        Upload file = uploadMapper.findMyById(fid, user.getUid());
        if(file == null) throw new APIException(ResponseCode.DATABASE_FAILED, "文件不存在或不属于该用户");
        FileUploadHelper.deleteFile(file.getPath());
        uploadMapper.deleteById(fid);
    }
}
